package com.heima.comment.service.impl;

import com.heima.comment.service.ApCommentHotService;
import com.heima.model.comment.pojos.ApComment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class ApCommentHotServiceImpl implements ApCommentHotService {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 异步计算热点评论
     * @param apComment
     */
    @Async("taskExecutor")
    @Override
    public void computeHotComment(ApComment apComment) {

        //1.查询热点评论列表（条件：type、objectId、flag  结果：likes倒序）  ap_comment
        List<ApComment> apCommentHotList = mongoTemplate.find(Query.query(Criteria.where("type").is(apComment.getType())
                .and("objectId").is(apComment.getObjectId())
                .and("flag").is(1)
        ).with(Sort.by(Sort.Direction.DESC,"likes")), ApComment.class);

        //2.热点评论列表数量不够5条，则直接将当前评论更新为热点评论
        if(apCommentHotList==null || apCommentHotList.size()<5){
            apComment.setFlag(1);
            apComment.setUpdatedTime(new Date());
            mongoTemplate.save(apComment);
        } else {
            //3.热点评论列表数量已够5条

            //3.1 取出热点评论列表中最后一条热点评论
            ApComment apCommentHotLast = apCommentHotList.get(apCommentHotList.size() - 1);

            //3.2 比较当前评论与最后热点评论的点赞数，比较成功就替换
            if(apComment.getLikes()>apCommentHotLast.getLikes()){
                // 更新当前评论为热点评论
                apComment.setFlag(1);
                apComment.setUpdatedTime(new Date());
                mongoTemplate.save(apComment);

                // 更新最后一条热点评论为普通评论
                apCommentHotLast.setFlag(0);
                apCommentHotLast.setUpdatedTime(new Date());
                mongoTemplate.save(apCommentHotLast);
            }

        }
    }
}
